package com.orange.cepmanagerweb.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.orange.cepmanagerweb.dao.PhoneDAO;
import com.orange.cepmanagerweb.model.Phone;
import com.orange.cepmanagerweb.util.Util;

@Service
public class PhoneService {

	private PhoneDAO PhoneDAO;
	private Util util;

	/**
	 * Get all Phones
	 * 
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Phone> getPhoneList() {

		return PhoneDAO.getPhones();
	}

	/**
	 * Create new Phone/Phones
	 * 
	 * @param data
	 *            - json data from request
	 * @return created Phones
	 */
	@Transactional
	public List<Phone> create(Object data) {

		List<Phone> newPhones = new ArrayList<Phone>();

		List<Phone> list = util.getPhonesFromRequest(data);

		for (Phone Phone : list) {
			newPhones.add(PhoneDAO.savePhone(Phone));
		}

		return newPhones;
	}

	/**
	 * Update Phone/Phones
	 * 
	 * @param data
	 *            - json data from request
	 * @return updated Phones
	 */
	@Transactional
	public List<Phone> update(Object data) {

		List<Phone> returnPhones = new ArrayList<Phone>();

		List<Phone> updatedPhones = util.getPhonesFromRequest(data);

		for (Phone Phone : updatedPhones) {
			returnPhones.add(PhoneDAO.savePhone(Phone));
		}

		return returnPhones;
	}

	/**
	 * Delete Phone/Phones
	 * 
	 * @param data
	 *            - json data from request
	 */
	@Transactional
	public void delete(Object data) {

		// it is an array - have to cast to array object
		if (data.toString().indexOf('[') > -1) {

			List<String> deletePhones = util.getListIdStringFromJSON(data);

			for (String id : deletePhones) {
				PhoneDAO.deletePhone(id);
			}

		} else { // it is only one object - cast to object/bean

			String id = data.toString();

			PhoneDAO.deletePhone(id);
		}
	}

	@Transactional
	public List<Phone> searchPhones(String name) {
		return PhoneDAO.searchPhones(name);
	}

	/**
	 * Spring use - DI
	 * 
	 * @param PhoneDAO
	 */
	@Autowired
	public void setPhoneDAO(PhoneDAO PhoneDAO) {
		this.PhoneDAO = PhoneDAO;
	}

	/**
	 * Spring use - DI
	 * 
	 * @param util
	 */
	@Autowired
	public void setUtil(Util util) {
		this.util = util;
	}
	}
